import errorCode from './errorCode.js'
import BASE_URL from "../config/api.js"
export const request = ({
	url,
	method,
	data,
	headers
}) => {
	uni.showLoading({
		title: '加载中'
	});
	const isToken = (headers || {}).isToken === false
	const Authorization = uni.getStorageSync('Authorization');
	let header;
	if (!isToken && Authorization) {
		header = {
			'Authorization': 'Bearer ' + Authorization
		}
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url,
			method,
			header,
			data,
			success(res) {
				const code = res.data.code || 200;
				// 获取错误信息
				const msg = errorCode[code] || res.data.msg || errorCode['default']
				switch (code) {
					case 401:
						uni.showModal({
							title: '系统提示',
							content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
							success: function(res) {
								if (res.confirm) {
									uni.reLaunch({
										url:"/pages/login/login"
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
						uni.removeStorageSync('Authorization');
						reject('无效的会话，或者会话已过期，请重新登录。')
						break;
					case 500:
						uni.showToast({
							title: msg,
							icon: "none"
						})
						reject(new Error(msg))
						break;
					case 601:
						uni.showToast({
							title: msg,
							icon: "none"
						})
						reject('error')
						break;
					case !200:
						uni.showToast({
							title: msg,
							icon: "none"
						})
						reject('error')
						break;
					default:
						resolve(res.data)

				}
			},
			fail(err) {
				reject(err);
				console.log(err)
			},
			complete() {
				uni.hideLoading();
			}
		});
	}).catch((e) => {});
};